/**
 * 品牌
 * 文件命名格式：zmn.模块名称.表名称.功能.jas
 * @author chongw
 * @date 2021/06/26
 */
layui.define(['index', 'form', 'table', 'laypage', 'layedit', 'laydate', 'jquery', 'zmnSelect', 'zmnApp', 'zmnBind'], function (exports) {
    let $ = layui.$;
    let table = layui.table;
    let laypage = layui.laypage;
    let laydate = layui.laydate;
    let form = layui.form;
    let zmnBind = layui.zmnBind;
    let zmnApp = layui.zmnApp;
    let zmnSelect = layui.zmnSelect;
    table.init('zmn-table', {
        toolbar: "#zmn-table-tool",
        page: true,
        defaultToolbar: json.showExportExcel ? ['exports'] : [],
        done: function () {
            $("div[lay-event='LAYTABLE_EXPORT']").attr('lay-event', 'CUSTOM_EXPORT');
        },
        limit: json.pageSize,
        height: 'full-149'
    });

    // 渲染日期范围选择器
    laydate.render({
        elem: '#timeSearch',
        range: true,
        min: json.dayLimit,
        max: 0,
        format: 'yyyy/MM/dd',
        trigger: 'click'
    });

    let engineerSearchItem = {
        init() {
            var objectName = json.objectName;
            if (objectName != null && objectName != '') {
                if (objectName.indexOf('<') >= 0) {
                    objectName = objectName.split("<")[0]
                }
            }
            zmnSelect.searchEngineer('objectId', {
                searchedValue: objectName,
                selectedValues: json.objectId,
                isRadio: true,
                remote: {
                    limitPermit: false,// json.vo.limitPermit,
                    events: {
                        extendParams: function () {
                            return {
                                //plat: 10,
                            }
                        }
                    }
                },
                events: {
                    changed: function (values) {
                        console.log("========engineerIds=========")
                        console.log("已选中的值:" + values)
                    }
                }
            });

            $('#engineerIds .xm-search-input').on('input propertychange', function () {
                json.vo.engineerSearchValue = $('#engineerIds .xm-search-input').val();
            });
        },
        /*convert(jsonData) {
            jsonData.engineerSearchValue = json.vo.engineerSearchValue;
            if (!zmnUtil.isEmptyNull(jsonData.engineerIds)) {
                jsonData.engineerIds = jsonData.engineerIds.split(",");
            } else {
                jsonData.engineerIds = [];
            }
        }*/
    };
    engineerSearchItem.init();
    laypage.render(zmnPage.laypageOptions(json));

    function initOrganizes(plat, orgThrId) {
        zmnSelect.selectlOrganizes({
            platSelectId: 'plat',
            orgThrSelectId: 'orgThrId'
        }, {
            platSelectId: {
                selectedValues: plat
            },
            orgThrSelectId: {
                selectedValues: orgThrId
            }
        }, {
            isRadio: true
        });
    }

    initOrganizes(json.plat, json.orgThrId);
    form.on('submit(zmn-form-submit)', function (obj) {
        //xm-input xm-search-input
        var objectName = $("#objectId .label-content").attr("title");
        $("#objectName").val(objectName);
    });

    $(".zmn-form-cancel").click(function () {
        initOrganizes(0, 0);
        clearSelect("objectId");
        let obj = {
            "plat": ""
            , "orgThrId": ""
            , "eventName": ""
            , "timeSearch": ""
            , "status": ""
            , "objectId": "",
            "objectName": ""

        };


        form.val('zmn-form', JSON.parse(JSON.stringify(obj)));
    });

    table.on("toolbar(zmn-table)", function (obj) {
        if (obj.event === 'CUSTOM_EXPORT') {
            $("#query-export").click();
        }
    })

    form.on('submit(query-export)', function (data) {
        if (json.exportLimit === null || json.exportLimit === 0) {
            layer.msg("您没有配置导出数量，无法导出", {"icon": 2});
            return false
        }
        let index = layer.load(1, {
            shade: [0.5, '#DBDBDB'] //0.1透明度的白色背景
        });
        let dataUrl = urlEncode(data.field);
        let fileName = "工程师监控数据.xlsx";
        zmnBrs.download("/brs/record/engineer/exportRecordExcel.action?" + dataUrl.slice(1), fileName, function () {
            layer.close(index);
        });
        return false;
    });

    //对外暴露的接口
    exports('brs_engineer_record_list', {});
});

let zmnBrs = {
    download(url, fileName = new Date().toISOString(), done = () => {
    }) {
        fetch(url, {
            credentials: 'include'
        }).then(res => res.blob().then(blob => {
            let a = document.createElement('a');
            let url = window.URL.createObjectURL(blob);
            let filename = fileName;
            a.href = url;
            a.download = filename;
            a.click();
            window.URL.revokeObjectURL(url);
            done(blob);
        }))
    }
}
/**
 * 清空值
 * @param itemId
 */
function clearSelect(itemId) {
    var selectItem = xmSelect.get('#' + itemId, true);
    selectItem.setValue([]);
}
/**
 * param 将要转为URL参数字符串的对象
 * key URL参数字符串的前缀
 * encode true/false 是否进行URL编码,默认为true
 *
 * return URL参数字符串
 */
let urlEncode = function (param, key, encode) {

    if (param == null) {
        return '';
    }
    let paramStr = '';
    let t = typeof (param);
    if (t === 'string' || t === 'number' || t === 'boolean') {
        paramStr += '&' + key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param);
    } else {
        for (let i in param) {
            let k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
            paramStr += urlEncode(param[i], k, encode);
        }
    }
    return paramStr;
};
